package com.apes.fn.scm.retailOrder.service.retailProcess;

import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.fn.server.workOrder.model.MaintenanceOrder;
import com.apes.fn.server.workOrder.repository.MaintenanceOrderRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.outbox.OutboxEventService;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apestech.framework.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wuq
 * @create 2021-05-25 9:53
 */
public abstract class ServerAndLossQuotationProcess extends CommonRetailDataProcess {

    @Autowired
    private ServicePlanItemRepository servicePlanItemRepository;

    @Autowired
    private MaintenanceOrderRepository maintenanceOrderRepository;

    public void updateItem(RetailOrder retailOrder) {

        retailOrder.getSaleItems().stream().forEach(item -> {
            String serverItemId = item.getOriginnumber();
            if (!StringUtils.hasText(serverItemId)) {
                throw new RuntimeException("服务方案来源，服务方案号不能为空");
            }
            ServicePlanItem servicePlanItem = servicePlanItemRepository.findOne(serverItemId);
            if (servicePlanItem == null) {
                throw new RuntimeException("服务方案：" + serverItemId + " 系统中不存在！");
            }

            item.setProductRule(servicePlanItem.calcProductRule());     //  根据服务方案明细来计算商品规则
            item.setLockPrice(servicePlanItem.getFloorPrice());//锁价
            item.setOriginalSalesUnitPrice(servicePlanItem.getPrimaryPriceUnit());//原销售单价
            item.setPftPriceUnit(servicePlanItem.getPriceUnit());  // 销售单价

            item.setMainSalesman(servicePlanItem.getMainSaler());   // 主、辅销
            item.setSubSalesman(servicePlanItem.getSupSaler());

            item.setLocation(servicePlanItem.getLocation());
            item.setPlatform(servicePlanItem.getPlatform());

            item.setReferTax(servicePlanItem.getReferTax());
            item.setSupplyChainManagement(servicePlanItem.getSupplyChainManagement());
            item.setEstimatedCommission(servicePlanItem.getEstimatedCommission());
            if (servicePlanItem.getParentServicePlanItem() != null) {
                throw new RuntimeException("该单为代门店施工商品,不允许在收银台收款!");
            }
            item.setRemark(servicePlanItem.getRemarks());

            if (item.getProductRule() == 10) {
                //获取服务工单
                List<String> slist = new ArrayList<>();
                slist.add("out");
                MaintenanceOrder maintenanceOrder = maintenanceOrderRepository.findFirstByServicePlanItemAndBusinessTypeNotIn(servicePlanItem, slist);
                if (maintenanceOrder != null) {
                    item.setSupplier(maintenanceOrder.getSupplier());
                    item.setInnerSalePriceUnit(maintenanceOrder.getPriceCostUnitInTax());   // 门店找车宝或者供应商采购价
                    item.setPriceOutUnitInTax(maintenanceOrder.getPlatformPriceCosInTax()); // 门店找车宝，车宝找供应商采购价
                    item.setContract(maintenanceOrder.getContract());
                }
            }
        });
    }

    public void callbackServicePlanFinished(RetailOrder retailOrder) {
        List<String> lists = retailOrder.getSaleItems().stream().map(RetailOrderItem::getOriginnumber).collect(Collectors.toList());
        //服务方案明细送
        OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
        wrapper.setSubscriber("servicePlan.server.receivablesList");
        wrapper.setAggregateId("SODID" + retailOrder.getId());
        try {
            wrapper.setPayload(JSON.toJSONString(lists));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);

    }
}
